import React, { Component, Fragment } from 'react';
import { Form, Input, Button, Row, Col , message} from 'antd';
import { MessageFilled, MobileFilled, UnlockFilled } from '@ant-design/icons';
import {withRouter} from 'react-router-dom'
// api
import {Login} from "../../api/account"

//组件
import Code from "../../components/code/index"

//方法
import {setToken} from '../../utils/session'


class LoginForm extends Component {
    loginF = React.createRef();
    constructor(props) {
        super(props);
        this.state = {
            username:''
        };
    }

    onFinish = async(values) => {
        let data = {
            username:values.username,
            password:values.passWord,
            code:values.code
        }
        await Login(data).then(res => {
            if(res.resCode === 0){
                message.success('登录成功！！')
                //存储token
                setToken(res.data.token);
                this.props.history.push('/home');
            }
        }).catch(e => {
            
        })
    };
    //获取邮箱
    getUsername = () => {
        let username = this.loginF.current.getFieldValue('username');
        this.setState({
            username,
        })
    };
    render() {
        const {username} = this.state;
        return (
            <Fragment>
                <Form
                    name="normal_login"
                    className="login-form"
                    ref={this.loginF}
                    initialValues={{ remember: true }}
                    onFinish={this.onFinish}
                >
                    <Form.Item name="username" rules={[{ required: true, message: '请输入手机号' }]}>
                        <Input onChange={this.getUsername} prefix={<MobileFilled className="site-form-item-icon" />} placeholder="请输入手机号" />
                    </Form.Item>
                    <Form.Item name="passWord" rules={[{ required: true, message: '请输入密码' }]}>
                        <Input prefix={<UnlockFilled className="site-form-item-icon" />} placeholder="请输入密码" />
                    </Form.Item>
                    <Form.Item name="code" rules={[{ required: true, message: '请输入验证码' }]}>
                        <Row getters={13}>
                            <Col span={15}><Input prefix={<MessageFilled className="site-form-item-icon" />} placeholder="请输入验证码" /></Col>
                            <Col span={8} offset={1}><Code username={username} type="login"></Code></Col>
                        </Row>
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit" className="login-form-button" block>登录</Button>
                    </Form.Item>
                </Form>
            </Fragment>
        )
    }
}
export default withRouter(LoginForm);